<template>
  <div class="userlist">
    <el-input
      placeholder="输入用户名或昵称"
      prefix-icon="el-icon-search"
      style="width: 200px; margin-bottom: 20px"
      v-model="search"
      @input="changeSearch"
      :fetch-suggestions="querySearchAsync"
    >
    </el-input>
    <el-button type="primary" v-if="addHide" @click="dialogFormVisible = true"
      >添加用户<i class="iconfont iconxinzeng"></i
    ></el-button>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        status-icon
        :rules="rules"
        ref="ruleForm"
        :model="ruleForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            placeholder="用户名"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            maxlength="15"
            placeholder="最大长度15位"
            v-model="ruleForm.nickname"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            placeholder="密码"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input
            type="password"
            placeholder="确认密码"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="quxiao('ruleForm')">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          :loading="subloading"
        >
          {{ subloading ? "提交中 ..." : "立即添加" }}</el-button
        >
      </div>
    </el-dialog>

    <div v-loading="loading" element-loading-text="加载中...">
      <el-table border :data="tableData" style="width: 100%; z-index: 10">
        <el-table-column label="用户名" prop="username" align="center" />
        <el-table-column label="昵称" prop="nickname" align="center" />
        <el-table-column label="头像" width="80" align="center">
          <template slot-scope="scope">
            <el-avatar :size="55" :src="scope.row.avatar">
              <img :src="scope.row.avatar" alt="" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="datetime" align="center" />
        <el-table-column
          label="状态"
          width="80"
          align="center"
          v-if="updateHide"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="statusGB(scope.$index, scope.row)"
              active-color="#13ce66"
              inactive-color=" #ccc"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          prop="operate"
          align="center"
          v-if="addshow"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              v-if="updateHide"
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              v-if="deleteHide"
              @click="handleDelete(scope.$index, scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              v-if="updateHide"
              @click="handleSet(scope.$index, scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-drawer
        :visible.sync="drawer"
        :with-header="false"
        :before-close="closedrawer"
      >
        <setupuser
          :setup="setup"
          :user="user"
          @drawers="drawers"
          @tables="handleUserList"
          ref="son"
        />
      </el-drawer>
    </div>
    <el-pagination
      :current-page="startPage"
      :page-size="pageSize"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      background
      layout="total,sizes,prev, pager, next"
      :total="this.total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  Apiuserlist,
  ApiuserlistStatus,
  ApiuserlistDelete,
  ApiAddUser,
  ApiLikeuser,
} from "../../../api/api";
import setupuser from "@/pages/home/users/setupuser";
export default {
  components: {
    setupuser,
  },
  data() {
    var validateUser = (rule, value, callback) => {
      let uPattern = /^[a-zA-Z][a-zA-Z0-9-_@.]{1,}$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (uPattern.test(value) == false) {
        callback(new Error("用户名以字母开头，不能有空格(账号可包含.@_-)"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.password !== "") {
          this.$refs.ruleForm.validateField("password");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      status: false,
      loading: true,
      sys_userlist: false,
      search: "",
      setup: "",
      user: {},
      //分页
      startPage: 1,
      pageSize: 10,
      total: 0,
      //增加用户
      subloading: false,
      dialogFormVisible: false,
      ruleForm: {
        username: "",
        nickname: "",
        pass: "",
        password: "",
      },
      rules: {
        username: [
          {
            validator: validateUser,
            trigger: "blur",
          },
        ],
        pass: [
          {
            validator: validatePass,
            trigger: "blur",
          },
        ],
        password: [
          {
            validator: validatePass2,
            trigger: "blur",
          },
        ],
      },

      drawer: false, //抽屉
      addshow: false,
      addHide: false,
      updateHide: false,
      deleteHide: false,
    };
  },

  created() {
    Apiuserlist().then((res) => {

      this.tableData = res.data;
      this.addshow =
        (res.qx.length == 1 && res.qx.indexOf(3) > -1 ) || res.qx.length ==0 ? false : true;
      // this.addshow =
      //   res.qx.length == 1 && res.qx.indexOf(3) > -1 ? true : false;

      this.addHide =
        res.qx.indexOf(1) > -1 ||
        res.qx.indexOf(2) > -1 ||
        res.qx.indexOf(3) > -1
          ? true
          : false;
      this.updateHide =
        res.qx.indexOf(1) > -1 ||
        res.qx.indexOf(2) > -1 ||
        res.qx.indexOf(4) > -1
          ? true
          : false;
      this.deleteHide =
        res.qx.indexOf(1) > -1 ||
        res.qx.indexOf(2) > -1 ||
        res.qx.indexOf(5) > -1
          ? true
          : false;
      this.total = res.count;
      this.loading = false;
    });
  },
  methods: {
    quxiao(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    closedrawer(done) {
      done();
      this.$refs.son.imageUrl = "";
    },
    changeSearch(e) {
      ApiLikeuser({
        keyword: e,
      }).then((res) => {
        this.loading = true;

        this.querySearchAsync(res);
      });
    },
    querySearchAsync(queryString) {
      var results = queryString.filter(
        (data) =>
          !this.search ||
          data.username.toLowerCase().includes(this.search.toLowerCase()) ||
          data.nickname.toLowerCase().includes(this.search.toLowerCase())
      );

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.tableData = results;
        this.loading = false;
      }, 1000 * Math.random());
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ApiAddUser({
            username: this.ruleForm.username,
            nickname: this.ruleForm.nickname,
            password: this.ruleForm.password,
          }).then((res) => {
            if (res.message == "用户已存在") {
              this.$message.error("用户已存在");
            } else {
              if (res.code == 400) {
                this.$message({
                  message: res.message,
                  type: "warning",
                });
              } else {
                if (this.subloading) {
                  return;
                }
                this.subloading = true;
                setTimeout(() => {
                  this.dialogFormVisible = false;
                  this.subloading = false;
                  this.$refs[formName].resetFields();
                  this.handleUserList();
                  this.total = this.total + 1;
                  this.$message({
                    message: "添加用户成功",
                    type: "success",
                  });
                }, 1500);
              }
            }
          });
        }
      });
    },
    handleCurrentChange(startPage) {
      this.startPage = startPage;
      this.handleUserList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.handleUserList();
    },
    handleUserList(data) {
      this.loading = true;

      Apiuserlist({
        currenPage: this.startPage,
        limit: this.pageSize,
      }).then((res) => {
        this.tableData = res.data || data;
        this.loading = false;
      });
    },

    statusGB(index, row) {
      ApiuserlistStatus({
        username: row.username,
        status: row.status,
      }).then((res) => {
        if (res.code == 400) {
          this.$message({
            message: res.message,
            type: "warning",
          });
        } else {
          this.$message({
            message: res.message,
            type: "success",
          });
        }
      });
    },
    handleEdit(index, row) {
      this.drawer = true;
      this.user = row;
      this.setup = "";
    },
    handleSet(index, row) {
      this.drawer = true;
      this.user = row;
      //切换到重置密码显示组件
      this.setup = "resetpass";
    },
    drawers(v) {
      this.drawer = v;
    },

    handleDelete(index, row) {
      this.$confirm(`将删除"${row.username}"此账号, 是否确定?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning",
        center: true,
      })
        .then(() => {
          ApiuserlistDelete({
            username: row.username,
          }).then((res) => {
            if (res.code == 400) {
              this.$message({
                message: res.message,
                type: "warning",
              });
            } else {
              this.handleUserList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.userlist >>> .el-avatar > img {
  margin: 0 auto;
}
</style>
